import { flysel, sync } from "../plugin/flysel.js"
import { style } from "./theme.js"
import { RGBA, takeColor } from "./tool.js"

const palette_box = flysel('#palette-box')
const palette = flysel('#palette')
const plate = palette.find('.palette-plate')
const pres = flysel('#palette .color-board')
const origPre = pres.get(0)
const nowPre = pres.get(1)

origPre.on('click', () => {
    form.now.fromObject(form.orig)
})

plate.on('mousedown,mousepressmove', (e) => {
    let { offsetX: x, offsetY: y } = e
    const w = plate.clientWidth
    x /= w
    y /= w
    if (x < 0) x = 0
    if (y < 0) y = 0
    if (x > 1) x = 1
    if (y > 1) y = 1
    form.now.setColor(...takeColor(x, y).slice(0, -1))
})

const rgbai = flysel('#colour-r, #colour-g, #colour-b, #alpha')
const GBC = {
    "r": [{ "a": 1, "r": 0 }, { "a": 1, "r": 255 }],
    "g": [{ "a": 1, "g": 0 }, { "a": 1, "g": 255 }],
    "b": [{ "a": 1, "b": 0 }, { "a": 1, "b": 255 }],
    "a": [{ "a": 0 }, { "a": 1 }]
}

const form = {
    orig: new RGBA(),
    /**@type {RGBA} */
    now: sync(new RGBA(), {
        form: palette,
        change() {
            setCssColor(nowPre, this.src)
            for (let i = 0; i < 'rgba'.length; i++) {
                const e = 'rgba'[i];
                const gbc = GBC[e].map(a => form.now.mergeString(a))
                rgbai.get(i).css('backgroundImage', `linear-gradient(90deg, ${gbc[0]} 0%, ${gbc[1]} 100%)`)
            }
        }
    }),
    src: null
}

const pos = {
    left: undefined,
    top: undefined
}

function setCssColor(e, v) {
    e.css('backgroundColor', v.toString())
}

export function openPalette(e) {
    form.src = e
    palette_box.block()
    if (pos.left === undefined || pos.top === undefined) {
        pos.left = (window.innerWidth - palette.width) / 2
        pos.top = (window.innerHeight - palette.height) / 2
    }
    Object.assign(palette, pos)
    form.orig.fromString(style[e])
    setCssColor(origPre, form.orig.toString())
    form.now.fromObject(form.orig)
}

flysel.body.on('click', function () {
    openPalette(this.attr('name'))
}, { entrust: '.color-set' })

palette.find('.abolish').on('click', () => {
    palette_box.hide()
})
palette.find('.apply').on('click', () => {
    style[form.src] = form.now.toString()
    form.src = null
    palette_box.hide()
})